import React, { useState, useEffect } from 'react'
import { Table, Button, Input, Modal, Form, message, Select, Space, Popconfirm } from 'antd';
import axios from 'axios';
export default function SaleManage() {
  const [dataSource, setDataSource] = useState([])
  const [goodsList, setGoodsList] = useState([])
  const [goodsSelect, setGoodsSelect] = useState([])
  const [messageApi, contextHolder] = message.useMessage();
  const [open, setOpen] = useState(false);
  const [nowItem, setNowItem] = useState("");
  const orderState = ["下单", "锁单", "生产中", "完成生产", "已发货"]
  useEffect(() => {
    getData()
  }, [])
  const getData = () => {
    axios.get("/sale/selectsale").then(res => {
      var data = []
      res.data.forEach(element => {
        data.push({ ...element.inteSaleorder, goodsname: element.goodsname })
      });
      setDataSource(data)
    })
    axios.get("/goods/selectall").then(res1 => {
      var data = []
      setGoodsList(res1.data)
      for (var i = 0; i < res1.data.length; i++) {
        data.push({
          value: i,
          label: res1.data[i].goodsname + res1.data[i].goodscode
        })
      }
      setGoodsSelect(data)
    })
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: "center",
      width: "10%",
      render: (text, record, index) => {
        return <span style={{ fontSize: "12px" }}>{index + 1}</span>
      }
    },
    {
      title: '订单名称',
      dataIndex: 'ordername',
      key: 'ordername',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '销售商品',
      dataIndex: 'goodsname',
      key: 'goodsname',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '商品数量',
      dataIndex: 'goodsnum',
      key: 'goodsnum',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '下单时间',
      dataIndex: 'ordertime',
      key: 'ordertime',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text}</span>
      }
    },
    {
      title: '生产开始时间',
      dataIndex: 'prostartime',
      key: 'prostartime',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text === null ? "无" : text}</span>
      }
    },
    {
      title: '生产完成时间',
      dataIndex: 'proendtime',
      key: 'proendtime',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text === null ? "无" : text}</span>
      }
    },
    {
      title: '发货时间',
      dataIndex: 'deliverytime',
      key: 'deliverytime',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{text === null ? "无" : text}</span>
      }
    },
    {
      title: '订单状态',
      dataIndex: 'orderstate',
      key: 'orderstate',
      align: "center",
      render: (text) => {
        return <span style={{ fontSize: "12px" }}>{orderState[text]}</span>
      }
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      fixed: 'right',
      align: "center",
      render: (text, item) => {
        return <Space>
          <Popconfirm
            title={"提示"}
            description={"确定锁定该订单?"}
            okText="确定"
            cancelText="取消"
            onConfirm={() => { lockOrder(item) }}
          >
            <a style={{ fontSize: "12px", color: item.orderstate === 0 ? "red" : "gray" }} disabled={!(item.orderstate === 0)}>{"锁单"}</a>
          </Popconfirm>
          <a style={{ fontSize: "12px", color: item.orderstate === 0 ? "#4e9dfd" : "gray" }} onClick={() => { if (item.orderstate === 0) { setOpen(true); setNowItem(item) } }} disabled={!(item.orderstate === 0)}>修改</a>
          <Popconfirm
            title={"删除"}
            description={"确定删除该订单?"}
            okText="确定"
            cancelText="取消"
            onConfirm={() => { deleteSale(item) }}
            disabled={!(item.orderstate < 2)}
          >
            <a style={{ fontSize: "12px", color: item.orderstate < 2 ? "red" : "gray" }} disabled={!(item.orderstate < 2)}>{"删除"}</a>
          </Popconfirm>

        </Space>
      }
    }
  ];
  const lockOrder = (item) => {
    if (item.orderstate === 0) {
      axios.get("/sale/setstate?id=" + item.id + "&&state=1").then(res => {
        if (res.data) {
          var data = [...dataSource]
          for (var d of data) {
            if (d.id === item.id) {
              d.orderstate = 1
            }
          }
          setDataSource(data)
        }
      })
    } else {
      messageApi.open({
        type: 'warning',
        content: '不可锁单！',
      });
    }

  }
  const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
    const [form] = Form.useForm();
    return (
      <Modal
        open={open}
        title={nowItem !== "" ? "修改订单" : "新增订单"}
        okText="确定"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            ordername: nowItem?.ordername,
            goodsvalue: nowItem === "" ? 0 : goodsList.findIndex(element => element.id === nowItem?.goodsid),
            goodsnum: nowItem?.goodsnum,
          }}
        >
          <Form.Item
            name="ordername"
            label="订单名称"
            rules={[
              {
                required: true,
                message: '未输入订单名称！',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="goodsvalue"
            label="销售商品"
            rules={[
              {
                required: true,
                message: '未输入销售商品！',
              },
            ]}
          >
            <Select
              options={goodsSelect}
            />
          </Form.Item>
          <Form.Item
            name="goodsnum"
            label="商品数量"
            rules={[
              {
                required: true,
                message: '未输入商品数量！',
              },
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    );
  };
  const onCreate = (values) => {
    if (nowItem !== "") {
      axios.post("/sale/update", {
        id: nowItem.id,
        ...values,
        goodsid: goodsList[values.goodsvalue].id
      }).then(res => {
        if (res.data) {
          messageApi.open({
            type: 'success',
            content: '修改成功',
          });
          goodsList.forEach(element1 => {
            if (res.data.goodsid === element1.id) {
              res.data.goodsname = element1.goodsname
            }
          });
          var nowdata = dataSource
          let targetObject = nowdata.find(obj => obj.id === nowItem.id);
          if (targetObject) {
            targetObject.ordername = values.ordername;
            targetObject.goodsid = res.data.goodsid;
            targetObject.goodsnum = values.goodsnum;
            targetObject.goodsname = res.data.goodsname;
          }
          setDataSource(nowdata)
          setNowItem("")
        }
      })
    } else {
      axios.post("/sale/insert", { ...values, goodsid: goodsList[values.goodsvalue].id }).then(res => {
        if (res.data) {
          messageApi.open({
            type: 'success',
            content: '添加成功',
          });
          goodsList.forEach(element1 => {
            if (res.data.goodsid === element1.id) {
              res.data.goodsname = element1.goodsname
            }
          });
          setDataSource([...dataSource, res.data])

        }
      })
    }

    setOpen(false);
  };
  const deleteSale = (item) => {
    console.log(item);
    if (item.orderstate < 1) {
      axios.get("/sale/delete?id=" + item.id).then(res => {
        if (res.data > 0) {
          messageApi.open({
            type: 'success',
            content: '删除成功',
          });
          setDataSource(dataSource.filter(res => { return res.id !== item.id }))
        }
      })
    } else {
      messageApi.open({
        type: 'warning',
        content: '不可删除！',
      });
    }

  }
  return (
    <div>
      <div >
        {contextHolder}

        <div style={{ display: 'flex' }}>
          <div style={{ flex: "1 1 100px" }}>
            <Button type="primary" onClick={() => { setOpen(true); }}>新增订单</Button>
          </div>
          <div style={{ flex: "1 1 100px", textAlign: "right" }}>
            <Button onClick={() => { getData() }}>刷新</Button>
          </div>
        </div>
        <Table
          columns={columns} dataSource={dataSource} style={{ margin: "5px 0 0 0" }}
          rowKey={(item) => item.id}
          pagination={{}}
          size='small'
        >
        </Table>
      </div>
      <CollectionCreateForm
        open={open}
        onCreate={onCreate}
        onCancel={() => {
          setOpen(false);
          setNowItem("")
        }}
      />
    </div>
  )
}
